//
//  ICCarouselView.swift
//  ICFoundationFramework
//
//  Created by cuichengcheng on 2017/11/29.
//  Copyright © 2017年 cuichengcheng. All rights reserved.
//
import UIKit


/// ICPageControl 位置
enum ICPageControlAlignment {
    case middle
    case left
    case right
    
}

class ICCarouselView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {
    var didSelectClo:((_ index:Int)->())? = nil
    private let carouselCellId = "carouselCellId"
    private var timer:Timer?
    //自定义pagecontrol
    private let pageControl = ICPageControl()
    /**
     hasTitle 是否有标题文字
     if set pageControlAlignment will be right
     default no title pageControlAlignment middle
     */
    var hasTitle = false {
        didSet{
            if hasTitle {
                pageControlAlignment = .right
            }
        }
    }
    //pageControl 默认 中间
    var pageControlAlignment:ICPageControlAlignment = .middle {
        didSet{
            pageControl.pageControlAlignment = pageControlAlignment
            textAlignment = .left
        }
    }
    //是否自动滚动
    var autoScroll = true {
        didSet{
            autoScroll ? invalidateTimer() : nil
        }
    }
    var imgs:Array<String> = [] {
        didSet{
            let list = imgs.map { (str) -> (img:String?, text:String?) in
                return (img:str, text:nil)
            }
            configData(list: list)
        }
    }
    
    //标题文字 alignment
    private var textAlignment:NSTextAlignment = .center
    //滚动方向 默认竖向滚动
    var scrollDirection:UICollectionViewScrollDirection  = .vertical {
        didSet{
            layout.scrollDirection = self.scrollDirection
            if self.scrollDirection == .vertical {
                self.scrollPosition = .top
                self.scrollLength = layout.itemSize.height
            }else {
                self.scrollPosition = .left
                self.scrollLength = layout.itemSize.width
            }
        }
    }
    private var titleW:CGFloat = 0
    private var scrollLength : CGFloat = 0
    private var scrollPosition : UICollectionViewScrollPosition = .top
    //即将滚动的下一页
    private var nextIndex:Int = 2 {
        didSet{
            if 0 <= nextIndex - 2 && nextIndex - 2 < dataSource.count - 2{
                pageControl.currentPage = nextIndex - 2
            }
            
        }
    }
    //自动滚动 间隔时长
    var timeDuration: TimeInterval = 2 {
        didSet{
            addTimer(timeDuration)
        }
    }
    
    private var dataSource:Array<(img:String?, text:String?)> = []
    private let layout = UICollectionViewFlowLayout();
    lazy var carouselCV:UICollectionView = {
        let cv = UICollectionView.init(frame: .zero, collectionViewLayout: self.layout);
        cv.backgroundColor = .clear
        cv.isPagingEnabled = true
        cv.delegate = self
        cv.dataSource = self
        cv.showsVerticalScrollIndicator = false;
        cv.showsHorizontalScrollIndicator = false;
        cv.register(ICCarouselCell.classForCoder(), forCellWithReuseIdentifier: carouselCellId)
        self.addSubview(cv)
        return cv;
    }();
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        carouselCV.frame = self.bounds;
        configSize(size: frame.size)
        pageControl.frame = CGRect(x: 0, y: frame.size.height-30, width: frame.size.width, height: 30)
        self.addSubview(pageControl)
        
    }

    func configSize(size:CGSize) {
        layout.itemSize = size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        scrollLength = size.height
        carouselCV.reloadData()
    }
    /**
     数据源 传入元组  text 为 nil 时 默认不显示文字，pagecontrol居中
     */
    func configData(list:Array<(img:String?, text:String?)>) {
        invalidateTimer()
        if list.count <= 0 {
            self.removeFromSuperview()
        }else {
            dataSource = list
            if list.count > 1 {
                dataSource.append(list.first!)
                dataSource.insert(list.last!, at: 0)
                addTimer(self.timeDuration)
            }
            pageControl.dotNum = list.count
            if list.first?.text != nil {
                hasTitle = true
                titleW = frame.size.width - pageControl.pageW
            }
            
            carouselCV.reloadData()
            DispatchQueue.main.asyncAfter(deadline: .now()+0.01, execute: {
                self.backOriginal()
            })
            
        }
    }

    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: carouselCellId, for: indexPath) as! ICCarouselCell
        cell.configData(dataSource[indexPath.item])
        cell.lab.isHidden = pageControlAlignment == .middle
        cell.bottomLayer.isHidden = pageControlAlignment == .middle
        cell.lab.textAlignment = textAlignment
        cell.labW = titleW
        cell.backgroundColor = color(indexPath.item%3)
        return cell
    }
    private func color(_ index:Int) -> UIColor {
        return [UIColor.brown, UIColor.blue, UIColor.orange][index]
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if didSelectClo != nil {
            didSelectClo!(pageControl.currentPage)
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        timerPause()
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        timerStart()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.scrollViewDidEndScrollingAnimation(scrollView)
        
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        setIndex()
    }

    private func setIndex() {
        var visibleItems = carouselCV.indexPathsForVisibleItems
        visibleItems = visibleItems.sorted(by: {$0.item > $1.item})
        nextIndex = (visibleItems.first?.item)! + 1
        if nextIndex >= dataSource.count {
            backOriginal()
        }
    }
    
    private func flipAnimate() {
        scrollToIndex(nextIndex)
        
    }
    
    private func scrollToIndex(_ index:Int) {
        carouselCV.scrollToItem(at: IndexPath(item: index, section: 0), at: scrollPosition, animated: true)
    }
    private func backOriginal() {
        self.carouselCV.setContentOffset(scrollDirection == .vertical ? CGPoint(x:0, y:scrollLength) : CGPoint(x:scrollLength, y:0), animated: false)
        nextIndex = 2
    }
    
    private func addTimer(_ timeInterval:TimeInterval) {
        guard timer != nil else {
            if autoScroll {
                timer = Timer(timeInterval: timeInterval, target: self, selector: #selector(timerRun), userInfo: nil, repeats: true)
                RunLoop.main.add(timer!, forMode: .commonModes)
            }
            return
        }
        print("timeDuration-- \(timeDuration)")

    }
    @objc func timerRun() {
        flipAnimate()
    }
    func timerPause() {
        timer?.fireDate = Date.distantFuture
    }
    func timerStart() {
        timer?.fire()
    }
    func invalidateTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    deinit {
        invalidateTimer()
        print("释放--%@",NSStringFromClass(self.classForCoder))
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
class ICCarouselCell: UICollectionViewCell {
    let imgV = UIImageView()
    let lab = UILabel()
    let bottomLayer = CALayer()
    var labW: CGFloat = 0 {
        didSet{
            var rect = lab.frame
            rect.size.width = labW
            lab.frame = rect
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        _initContentSubviews()
    }
    func _initContentSubviews() {
        imgV.contentMode = .scaleAspectFill
        imgV.layer.masksToBounds = true
        self.contentView.addSubview(imgV)
        
        
        bottomLayer.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6).cgColor
        bottomLayer.frame = CGRect(x: 0, y: self.contentView.bounds.size.height-30, width: self.contentView.bounds.size.width, height: 30)
        self.contentView.layer.addSublayer(bottomLayer)
        
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        lab.textColor = .white
        self.contentView.addSubview(lab)
                
        imgV.frame = self.contentView.bounds
        lab.frame = CGRect(x: 10, y: bottomLayer.frame.origin.y, width: bottomLayer.bounds.size.width, height: bottomLayer.bounds.size.height)
    }
    func configData(_ tuple:(img:String?, text:String?)) {
        if let img = tuple.img {
            if (img.hasPrefix("http://")) {
                imgV.kf.setImage(with: URL(string: img))
            }else {
                imgV.image = UIImage(named: img)
            }
        }
        lab.text = tuple.text
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
class ICCarouselContentView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
//        self.backgroundColor = .clear
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
